var Q = require('q'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    assemblyRelationController = require('../../../Barcode/server/controllers/AssemblyRelation.server.controller'),
    MOController = require('../../../ProduceReady/server/controllers/MO.server.contorller');

//获取批次
exports.getMOLotNumber = function(req, res) {
    MOController.getMOLotNumber(function(err, result) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        res.json({
            Data: result,
            Error: null
        });
    });
};


//批次绑定
exports.MOLotNumberToAssemblyBarcode = function(req, res) {
    var parameter = req.body.Parameter,
        Barcode = parameter.Barcode,
        SecurityId = parameter.SecurityId,
        Molot = parameter.Molot;
    //尺寸稍后添加

    var barcodeMasterData = {
        Barcode: SecurityId,
        BarcodeType: 0,
        IsAssembly: true
            //外部条码标识待定
            //todo
    };

    //查询主档中是否存在要插入的镭射标
    findOneBarcodeMaster(barcodeMasterData.Barcode).then(function(result) {
        if (result) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '镭射标占用';
            newErr.message = '主档中存在当前镭射标！';
            res.json({
                Data: null,
                Error: newErr
            });
            return;
        }
        //将镭射标插入到主档中
        barcodeMasterController.createBarcodeMaster(barcodeMasterData, function(err, barcodeMasterRecord) {
            if (err || !barcodeMasterRecord || barcodeMasterRecord == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '创建条码主档失败';
                newErr.message = '创建条码主档失败！';
                res.json({
                    Data: null,
                    Error: newErr
                });
                return;
            }

            findOneBarcodeMaster(Barcode).then(function(result) {
                var assemblyRelation = {
                    BarcodeMaster: result._id,
                    AssemblyBarcode: barcodeMasterRecord._id,
                    AssemblyType: 0
                };
                assemblyRelationController.createAssemblyRelation(assemblyRelation, function(err, assemblyRelationRecord) {
                    if (err) {
                        barcodeMasterController.deleteById(barcodeMasterRecord._id, function(err) {
                            if (err) {
                                var newErr = new Error();
                                newErr.leval = 9;
                                newErr.title = '回滚删除条码主档失败';
                                newErr.message = '回滚删除条码主档失败！';
                                res.json({
                                    Data: null,
                                    Error: newErr
                                });
                            } else {
                                var newErr = new Error();
                                newErr.leval = 9;
                                newErr.title = '创建装配关系失败';
                                newErr.message = '创建装配关系失败！';
                                res.json({
                                    Data: null,
                                    Error: newErr
                                });
                            }
                        });
                        return;
                    }
                    barcodeMasterController.updateByValue({ Barcode: Barcode }, { ShipLotNumber: Molot }, function(err, results) {
                        if (err) {
                            var assemblyRelationArr = [],
                                barcodeMasterArr = [],
                                assemblyObj = {},
                                barcodeMasterObj = {};
                            assemblyObj.RowStatus = PublicEnum.RowStatus.Delete;
                            assemblyObj._id = assemblyRelationRecord._id;
                            assemblyRelationArr.push(assemblyObj);

                            barcodeMasterObj.RowStatus = PublicEnum.RowStatus.Delete;
                            barcodeMasterObj._id = barcodeMasterRecord._id;
                            barcodeMasterArr.push(barcodeMasterObj);
                            Transaction.BatchSaveByTran(
                                [
                                    { EntityName: 'AssemblyRelation', Records: assemblyRelationArr },
                                    { EntityName: 'BarcodeMaster', Records: barcodeMasterArr }
                                ],
                                function(err) {
                                    if (err) {
                                        var newErr = new Error();
                                        newErr.leval = 9;
                                        newErr.title = '回滚删除条码主档和装配关系失败';
                                        newErr.message = '回滚删除条码主档和装配关系失败！';
                                        res.json({
                                            Data: null,
                                            Error: newErr
                                        });
                                    } else {
                                        var newErr = new Error();
                                        newErr.leval = 9;
                                        newErr.title = '更新条码主档失败';
                                        newErr.message = '更新条码主档失败！';
                                        res.json({
                                            Data: null,
                                            Error: newErr
                                        });
                                    }
                                }
                            );
                        } else {
                            res.json({
                                Data: results,
                                Error: null
                            });
                        }
                    });

                });
            }, function(err) {
                res.json({
                    Data: null,
                    Error: err
                });
            });
        });

    }, function(err) {
        res.json({
            Data: null,
            Error: err
        });
    });

};

//查询某一个主档信息
function findOneBarcodeMaster(barcode) {
    var deferred = Q.defer();
    barcodeMasterController.findAssemblyBarcodeMasterId(barcode, function(err, result) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(result)
        }
    });
    return deferred.promise;
}
